# -*- coding: utf-8 -*-

from django import forms
from django.contrib.auth.models import User

class FormCadastrar(forms.ModelForm):
    
    class Meta:
        model = User
        
        fields = ('username', 'email', 'password')
        
    confirme_a_senha = forms.CharField(max_length = 30, widget = forms.PasswordInput)
        
    def __init__(self, *args, **kwargs):
        self.base_fields['password'].help_text = ""
        self.base_fields['username'].help_text = ""
        self.base_fields['password'].widget = forms.PasswordInput()
        super(FormCadastrar, self).__init__(*args, **kwargs)
        
    def clean_username(self):
        
        if(User.objects.filter(username = self.cleaned_data['username']).count()):
            raise forms.ValidationError('Ja existe um usuário com este username')
        
        return self.cleaned_data['username']
    
    def clean_email(self):
        
        if(User.objects.filter(email = self.cleaned_data['email']).count()):
            raise forms.ValidationError('Ja existe um usuário com este email')
        
        return self.cleaned_data['email']
    
    def clean_confirme_a_senha(self):
        
        if(self.cleaned_data['confirme_a_senha'] != self.cleaned_data['password']):
            raise forms.ValidationError('As senhas não conferem!')
        
        return self.cleaned_data['confirme_a_senha']
    
    def save(self, commit=True):
        usuario = super(FormCadastrar, self).save(commit=False)
        usuario.set_password(self.cleaned_data['password'])
        
        if(commit):
            usuario.save()
        
        return usuario

class DefinitionErrorList(forms.util.ErrorList):
    
    def __unicode__(self):
        return self.view_as_dd()
    
    def view_as_dd(self):
        if not self:
            return u''
        
        return u'<'